<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-input
          v-model="queryForm.name"
          placeholder="请输入任务名称"
          clearable
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-select
          v-model="queryForm.enabled"
          placeholder="状态"
          clearable
          style="width: 120px"
          class="filter-item"
        >
          <el-option label="启用" value="true" />
          <el-option label="禁用" value="false" />
        </el-select>
        <el-button
          class="filter-item"
          type="primary"
          :icon="Search"
          @click="handleFilter"
        >查询</el-button>
        <el-button
          class="filter-item"
          type="info"
          :icon="RefreshRight"
          @click="resetQuery"
        >重置</el-button>
        <el-button
          class="filter-item"
          type="success"
          :icon="Plus"
          @click="handleCreate"
        >新增</el-button>
        <el-button
          class="filter-item"
          type="danger"
          :icon="Delete"
          @click="batchDelete"
          :disabled="selectedRows.length === 0"
        >批量删除</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="taskList"
        border
        style="width: 100%; margin-bottom: 20px; table-layout: fixed;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column prop="id" label="任务ID" width="60" align="center" />
        <el-table-column prop="name" label="任务名称" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="task_func" label="任务函数" width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="enabled" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
              {{ scope.row.enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="位置参数"  width="120" align="center">
          <template #default="scope">
            <el-tag>{{ formatArgs(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关键字参数" width="120" align="center" >
          <template #default="scope">
            <el-tag>{{ formatKwargs(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="celery_task_id" label="Celery任务ID" width="120" align="center" show-overflow-tooltip />
        <el-table-column label="最后成功时间" prop="last_success_time" width="160" align="center">
          <template #default="scope">
            <el-tag v-if="lastSuccessMap[scope.row.name]">{{ lastSuccessMap[scope.row.name] }}</el-tag>
            <el-tag v-else type="info">加载中...</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联任务定义" width="200" align="center">
          <template #default="scope">
            <el-popover
              placement="top"
              trigger="hover"
              :width="300"
              v-if="taskDefinitionDetails[scope.row.task_definition]"
            >
              <template #default>
                <div>
                  <p><strong>名称:</strong> {{ taskDefinitionDetails[scope.row.task_definition].name }}</p>
                  <p><strong>类型:</strong> {{ taskDefinitionDetails[scope.row.task_definition].task_type }}</p>
                  <p v-if="taskDefinitionDetails[scope.row.task_definition].task_type === 'crontab'">
                    <strong>Crontab:</strong> {{ formatCrontab(taskDefinitionDetails[scope.row.task_definition]) }}
                  </p>
                  <p v-if="taskDefinitionDetails[scope.row.task_definition].task_type === 'interval'">
                    <strong>间隔:</strong> {{ taskDefinitionDetails[scope.row.task_definition].interval_time }} {{ formatIntervalUnit(taskDefinitionDetails[scope.row.task_definition].interval_unit) }}
                  </p>
                  <p v-if="taskDefinitionDetails[scope.row.task_definition].task_type === 'clock'">
                    <strong>时间:</strong> {{ taskDefinitionDetails[scope.row.task_definition].clock_time }}
                  </p>
                  <p v-if="taskDefinitionDetails[scope.row.task_definition].description">
                    <strong>描述:</strong> {{ taskDefinitionDetails[scope.row.task_definition].description }}
                  </p>
                </div>
              </template>
              <template #reference>
                <el-tag>{{ taskDefinitionMap[scope.row.task_definition] }}</el-tag>
              </template>
            </el-popover>
            <el-tag v-else type="info">加载中...</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">
            <el-button type="info" size="small" @click="handleDetail(scope.row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleRunNow(scope.row)" :disabled="!scope.row.enabled">执行</el-button>
            <el-button 
              :type="scope.row.enabled ? 'warning' : 'success'" 
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.enabled ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-show="total > 0"
        background
        v-model:current-page="queryForm.page"
        v-model:page-size="queryForm.page_size"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog :title="dialogTitle" v-model="detailDialogVisible" width="600px">
      <el-form :model="detailForm" ref="detailFormRef" label-width="120px">
        <el-form-item label="任务ID" prop="id">
          <el-input v-model="detailForm.id" disabled />
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="detailForm.name" disabled />
        </el-form-item>
        <el-form-item label="任务函数" prop="task_func">
          <el-input v-model="detailForm.task_func" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
           <el-tag :type="detailForm.enabled ? 'success' : 'danger'">
             {{ detailForm.enabled ? '启用' : '禁用' }}
           </el-tag>
        </el-form-item>
        <el-form-item label="任务定义名称" prop="task_definition_name">
          <el-input v-model="detailForm.task_definition_name" disabled />
        </el-form-item>
        <el-form-item label="任务定义详情" prop="task_definition_details_formatted">
          <el-input type="textarea" :rows="3" v-model="detailForm.task_definition_details_formatted" disabled />
        </el-form-item>
        <el-form-item label="位置参数" prop="task_args">
          <el-input type="textarea" :rows="3" v-model="detailForm.task_args" disabled />
        </el-form-item>
        <el-form-item label="关键字参数" prop="task_kwargs">
          <el-input type="textarea" :rows="3" v-model="detailForm.task_kwargs" disabled />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" :rows="2" v-model="detailForm.description" disabled />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="detailForm.creator" disabled />
        </el-form-item>
        <el-form-item label="创建时间" prop="create_time">
          <el-input v-model="detailForm.create_time" disabled />
        </el-form-item>
        <el-form-item label="更新人" prop="updater">
          <el-input v-model="detailForm.updater" disabled />
        </el-form-item>
        <el-form-item label="更新时间" prop="update_time">
          <el-input v-model="detailForm.update_time" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加/编辑对话框组件 -->
    <TaskDialog 
      v-model="dialogVisible" 
      :task-data="currentTaskData"
      :available-tasks="availableTasks"
      :task-definitions="taskDefinitions"
      @refresh="getTaskList"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Tools, RefreshRight, Edit, Delete, Plus } from '@element-plus/icons-vue'
import requestUtil, {getServerUrl} from '@/util/request'
import TaskDialog from './components/dialog.vue'

// 数据列表
const loading = ref(false)
const taskList = ref([])
const total = ref(0)
const selectedRows = ref([])

// 表单数据
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const detailFormRef = ref(null)
const currentTaskData = ref({})

const detailForm = reactive({
  id: undefined,
  name: '',
  task_func: '',
  task_definition_name: '',
  task_definition_details_formatted: '',
  task_args: '',
  task_kwargs: '',
  enabled: true,
  description: '',
  creator: '',
  create_time: '',
  updater: '',
  update_time: ''
})

const form = reactive({
  id: undefined,
  name: '',
  task_func: '',
  task_args: '[]',
  task_kwargs: '{}',
  enabled: true,
  description: '',
  task_definition: undefined
})

// 可用任务列表
const availableTasks = ref([])
// 任务定义列表
const taskDefinitions = ref([])

// 查询参数
const queryForm = ref({
  name: '',
  page: 1,
  page_size: 10
})

const formatArgs = (row) => {
  if (row.task_args && row.task_args.length > 0) {
    return JSON.stringify(row.task_args)
  }
  return '无参数'
}

// 格式化参数显示
const formatKwargs = (row) => {
  console.log("task_kwargs:",row.task_kwargs)
  if (row.task_kwargs && JSON.stringify(row.task_kwargs).length > 0) {
      return JSON.stringify(row.task_kwargs)
  //   result += `关键字参数: ${JSON.stringify(JSON.parse(row.task_kwargs))}`
  }
  return '无参数'
}

// 任务定义映射表
const taskDefinitionMap = ref({})
// 任务定义详情映射表
const taskDefinitionDetails = ref({})

// 获取单个任务定义
const getTaskDefinitionName = async (id) => {
  if (!id) return
  
  try {
    const response = await requestUtil.get(`tasks/task_definitions/${id}/`)
    taskDefinitionMap.value[id] = response.name
    taskDefinitionDetails.value[id] = response
  } catch (error) {
    console.error('获取任务定义失败', error)
    taskDefinitionMap.value[id] = '获取失败'
  }
}

// 格式化Crontab显示
const formatCrontab = (definition) => {
  if (!definition) return ''
  return `${definition.minute} ${definition.hour} ${definition.day_of_month} ${definition.month_of_year} ${definition.day_of_week}`
}

// 格式化时间间隔单位
const formatIntervalUnit = (unit) => {
  const unitMap = {
    'days': '天',
    'hours': '小时',
    'minutes': '分钟',
    'seconds': '秒',
    'microseconds': '微秒'
  }
  return unitMap[unit] || unit
}

// 格式化任务定义详情
const formatTaskDefinitionDetail = (definition) => {
  if (!definition) return ''
  
  if (definition.task_type === 'crontab') {
    return `Crontab: ${formatCrontab(definition.crontab_detail)}`
  } else if (definition.task_type === 'interval') {
    return `间隔: ${definition.interval_detail.every} ${formatIntervalUnit(definition.interval_detail.period)}`
  } else if (definition.task_type === 'clock') {
    return `时间: ${definition.clocked_detail.clocked_time}`
  }
  
  return definition.task_type
}

// last_success_time映射表
const lastSuccessMap = ref({})

// 获取last_success_time
const getLastSuccessTime = async (task) => {
  if (!task || !task.id) return
  
  try {
    // 使用 tasks_instance_id 精确查询该任务的执行结果
    const response = await requestUtil.get('tasks/task_result/last_success_task_results', {
      "periodic_task_name": task.name,
    })
    
    if (response.date_done) {
      lastSuccessMap.value[task.name] = response.date_done
    } else {
      lastSuccessMap.value[task.name] = '无成功记录'
    }
  } catch (error) {
    console.error('获取last_success_time失败', error)
    lastSuccessMap.value[task.name] = '获取失败'
  }
}

// 获取任务列表
const getTaskList = async () => {
  loading.value = true
  try {
    if (queryForm.value.name) {
      queryForm.value.page=1
    }
    const response = await requestUtil.get('tasks/tasks/', queryForm.value)
    taskList.value = response.results
    total.value = response.count
    
    // 获取任务定义名称
    for (const task of taskList.value) {
      if (task.task_definition && !taskDefinitionMap.value[task.task_definition]) {
        getTaskDefinitionName(task.task_definition)
      }
    }

    // 获取last_success_time
    for (const task of taskList.value) {
      getLastSuccessTime(task)
    }    
  } catch (error) {
    console.error('获取任务列表失败', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 获取可用任务列表
const getAvailableTasks = async () => {
  try {
    const response = await requestUtil.get('tasks/tasks/available_tasks/')
    availableTasks.value = response
  } catch (error) {
    console.error('获取可用任务列表失败', error)
    ElMessage.error('获取可用任务列表失败')
  }
}

// 获取任务定义列表
const getTaskDefinitions = async () => {
  try {
    const response = await requestUtil.get('tasks/task_definitions/')
    taskDefinitions.value = response.results
  } catch (error) {
    console.error('获取任务定义列表失败', error)
    ElMessage.error('获取任务定义列表失败')
  }
}


// 处理查询
const handleFilter = () => {
  queryForm.value.page = 1
  getTaskList()
}

// 重置查询
const resetQuery = () => {
  queryForm.value.name = ''
  queryForm.value.enabled = ''
  queryForm.value.page = 1
  getTaskList()
}

// 处理选择变更
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理页码变更
const handleSizeChange = (size) => {
  queryForm.value.page_size = size
  getTaskList()
}

// 处理页数变更
const handleCurrentChange = (page) => {
  queryForm.value.page = page
  getTaskList()
}

// 处理创建
const handleCreate = () => {
  currentTaskData.value = {}
  dialogVisible.value = true
}

// 处理详情
const handleDetail = (row) => {
  dialogTitle.value = '任务详情'
  
  detailForm.id = row.id
  detailForm.name = row.name
  detailForm.task_func = row.task_func
  
  if (row.task_definition && taskDefinitionDetails.value[row.task_definition]) {
    const defDetails = taskDefinitionDetails.value[row.task_definition];
    detailForm.task_definition_name = defDetails.name;
    detailForm.task_definition_details_formatted = formatTaskDefinitionDetail(defDetails);
  } else {
    detailForm.task_definition_name = 'N/A';
    detailForm.task_definition_details_formatted = 'N/A';
  }
  
  detailForm.task_args = row.task_args ? JSON.stringify(row.task_args, null, 2) : '[]'
  detailForm.task_kwargs = row.task_kwargs ? JSON.stringify(row.task_kwargs, null, 2) : '{}'
  detailForm.enabled = row.enabled
  detailForm.description = row.description || '' // 确保 description 不是 undefined
  detailForm.creator = row.creator
  detailForm.create_time = row.create_time
  detailForm.updater = row.updater
  detailForm.update_time = row.update_time
  
  detailDialogVisible.value = true // 修正：应控制详情对话框的显示
}

// 处理编辑
const handleEdit = (row) => {
  currentTaskData.value = { ...row }
  dialogVisible.value = true
}

// 处理批量删除
const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的任务')
    return
  }
  
  const taskNames = selectedRows.value.map(row => row.name).join('、')
  
  ElMessageBox.confirm(
    `确认删除以下 ${selectedRows.value.length} 个任务吗？<br/><br/>${taskNames}`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }
  ).then(async () => {
    try {
      // 并发删除所有选中的任务
      const deletePromises = selectedRows.value.map(row => 
        requestUtil.del(`tasks/tasks/${row.id}/`)
      )
      
      await Promise.all(deletePromises)
      
      ElMessage.success(`成功删除 ${selectedRows.value.length} 个任务`)
      selectedRows.value = [] // 清空选中项
      getTaskList()
    } catch (error) {
      console.error('批量删除任务失败', error)
      ElMessage.error('批量删除任务失败')
    }
  }).catch(() => {})
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除任务 "${row.name}" 吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.del(`tasks/tasks/${row.id}/`)
      ElMessage.success('删除成功')
      getTaskList()
    } catch (error) {
      console.error('删除任务失败', error)
      ElMessage.error('删除任务失败')
    }
  }).catch(() => {})
}

// 处理立即执行
const handleRunNow = (row) => {
  ElMessageBox.confirm(`确认立即执行任务 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const response = await requestUtil.post(`tasks/tasks/${row.id}/run_now/`)
      ElMessage.success(`任务已提交执行，任务ID: ${response.task_id}`)
    } catch (error) {
      console.error('执行任务失败', error)
      ElMessage.error('执行任务失败')
    }
  }).catch(() => {})
}

// 处理启用/禁用状态切换
const handleToggleStatus = (row) => {
  const action = row.enabled ? 'disable' : 'enable'
  const actionText = row.enabled ? '禁用' : '启用'
  
  ElMessageBox.confirm(`确认${actionText}任务 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await requestUtil.post(`/tasks/tasks/${row.id}/${action}/`)
      ElMessage.success(`${actionText}成功`)
      getTaskList()
    } catch (error) {
      console.error(`${actionText}任务失败`, error)
      ElMessage.error(`${actionText}任务失败`)
    }
  }).catch(() => {})
}


// 页面加载时获取数据
onMounted(() => {
  getTaskList()
  getAvailableTasks()
  getTaskDefinitions()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>
